package cn.edu.scau.cmi.maintain.service;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.domain.Picture;

@Service("PictureMaintenceService")
@Transactional(timeout=300000000)
public class PictureMaintenceServiceImpl extends CmiEmaController implements PictureMaintenceService {

//	更新数据库中图片的路径和文件名的缺陷，保证数据可以正常的在前端获取
	
	@Override
	public void updatePathAndFilename(Picture picture) throws IOException {
		// 如果是事件的图片
//		(1) 文件重命名
		String destFileName;
		File destFile;
		
		File srcFile = new File("D:\\EMA工作目录\\Image\\已经审核\\" + picture.getPath());
		System.out.println(srcFile.getName());
		
		String[] srcFileSuffixArray = picture.getPath().split("\\.");
		String srcFileSuffix = srcFileSuffixArray[srcFileSuffixArray.length - 1];

		if (picture.getEvent() != null) {
//			(1)picture表的path的修改
//			TODO 有的事件u哟多个图片，需要考虑，目前测试没有考虑
			destFileName = "event_" + picture.getEvent().getId()+"_"+picture.getName() + "_"
					+picture.getId() + "." + srcFileSuffix;
			destFile = new File("D:\\EMA工作目录\\Image\\已经审核\\" + destFileName);
			
		} else {
//			(2)picture表的path的修改
			destFileName = "food_" + picture.getFood().getId()+"_"+picture.getName()+ "_"
					+picture.getId() + "." + srcFileSuffix;
			destFile = new File("D:\\EMA工作目录\\Image\\已经审核\\" + destFileName);
			
		}

//		注意了，有的文件名不合符规范导致出错，千万注意！！！，需要处理这些异常。
//		已经整理好了的话就不需要重新整理了
		if(srcFile.getName().equalsIgnoreCase(destFile.getName())) {
			FileUtils.copyFile(srcFile, destFile);
			FileUtils.deleteQuietly(srcFile);
			System.out.println(picture.getId()+"， "+picture.getName()+"已经修改！！！");
		}
		
		picture.setPath(destFileName);
		pictureService.savePicture(picture);
	}
}